package com.example.baseappstore.ui.adapter;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.example.baseappstore.databinding.DialogProgressBinding;
import com.example.baseappstore.databinding.RvUpdateItemBinding;
import com.example.baseappstore.domain.response.RecommendBean;
import com.example.baseappstore.utils.net.CommonUtils;
import com.example.baseappstore.utils.net.OkHttpUtils;
import com.example.baseappstore.utils.net.OkResult;

import java.io.File;
import java.util.List;

public class UpdateAdapter extends RecyclerView.Adapter<UpdateAdapter.MyViewHolder> {

    private List<RecommendBean> list;
    private DialogProgressBinding binding;
    private AlertDialog alertDialog;

    public UpdateAdapter(List<RecommendBean> list) {
        this.list = list;
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
        RvUpdateItemBinding binding = RvUpdateItemBinding.inflate(layoutInflater, parent, false);
        return new MyViewHolder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        RecommendBean data = list.get(position);
        holder.binding.tvTitle.setText(data.getApkName());
        holder.binding.tvIntro.setText(data.getIntroduce());
        Glide.with(holder.itemView).load(OkHttpUtils.BASE_URL + "/dev-api" + data.getLogoPic()).into(
                holder.binding.imageView
        );
        String apkPath = Environment.getExternalStorageDirectory().getPath()
                + File.separator + "Download" + File.separator + data.getApkName() + ".apk";
        File downLoadFile = new File(apkPath);
        int mb = ((int) (Float.parseFloat(data.getApkSize().split("MB")[0]) * 100));
        holder.binding.button.setOnClickListener(v -> {
            createDialog(holder.itemView.getContext(), mb, OkHttpUtils.BASE_URL + "/dev-api" + data.getLogoPic());
            if (!alertDialog.isShowing()) {
                alertDialog.show();
            }
            OkHttpUtils.downloadFile(OkHttpUtils.BASE_URL + "/dev-api" + data.getDownloadPath(), downLoadFile, new OkResult() {
                @Override
                public void onSuccess(String data) {
                    float progressF = Float.parseFloat(data);
                    int progress = ((int) (progressF * 100));
                    holder.binding.tvTitle.post(() -> {
                        binding.tvProgress.setText(new StringBuilder().append("当前已下载")
                                .append(progressF).append("MB"));
                        binding.progressBar.setProgress(progress);
                        if(progress==mb){
                            CommonUtils.showToast("下载完成");
                            alertDialog.dismiss();
                        }
                    });
                }
            });
        });

    }

    @Override
    public int getItemCount() {
        return list.size();
    }


    protected class MyViewHolder extends RecyclerView.ViewHolder {
        final RvUpdateItemBinding binding;

        public MyViewHolder(RvUpdateItemBinding binding) {
            super(binding.getRoot());
            this.binding = binding;

        }
    }


    private void createDialog(Context context, int maxSize, String imagePath) {
        binding = DialogProgressBinding.inflate(LayoutInflater.from(context));
        binding.progressBar.setMax(maxSize);
        Glide.with(binding.imageview).load(imagePath).into(binding.imageview);
        binding.btnCheckProgress.setOnClickListener(v -> {
            //打开默认的下载文件夹
            Uri uri = Uri.parse(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString());
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(uri, "*/*");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // 在新任务中启动Activity
            intent.addCategory(Intent.CATEGORY_DEFAULT);
            context.startActivity(intent);
        });
    }


}
